<!-- 商品添加 -->
<template>
  <h2 style="color: #595959; margin-bottom: 20px">
    {{ $t("messages.ProductAdd") }}
  </h2>

  <el-form :model="form" label-width="100px">
    <el-form-item label="商品名称">
      <el-input v-model="form.name" style="width: 400px"></el-input>
    </el-form-item>
    <el-form-item label="所属分类">
      <el-input v-model="form.category" style="width: 400px"></el-input>
    </el-form-item>
    <el-form-item label="商品价格">
      <el-input-number
        style="width: 400px"
        v-model="form.price"
        :min="1"
        :max="20"
        @change="handleChange"
      />
    </el-form-item>
    <el-form-item label="商品描述">
      <el-input
        type="textarea"
        style="width: 400px"
        v-model="form.goodsDesc"
      ></el-input>
    </el-form-item>
    <el-form-item label="商品图片">
      <el-upload
        class="avatar-uploader"
        action="http://127.0.0.1:5000/goods/goods_img_upload"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <img v-if="form.imgUrl" :src="form.imgUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
    </el-form-item>
    <el-form-item>
      <el-button
        type="primary"
        @click="submitForm"
        style="width: 100px; height: 40px"
        >添加商品</el-button
      >
    </el-form-item>
  </el-form>
</template>

<script setup>
import { reactive } from "vue";
import { ElMessage } from "element-plus";
// 接口
import { addGoods } from "@/api/index.js";

const form = reactive({
  name: "",
  category: "",
  price: 0,
  goodsDesc: "",
  imgUrl: "",
});

// 添加接口
const addGoodsFn = async () => {
  const res = await addGoods(form);
  if (res.code === 0) {
    ElMessage({
      type: "success",
      message: "添加成功",
    });
  } else {
    ElMessage({
      type: "error",
      message: "添加失败，请重新填写",
    });
  }
};

const handleChange = (value) => {
  console.log(value);
};

const handleAvatarSuccess = (response, file) => {
  // 处理上传成功
  form.imgUrl = URL.createObjectURL(file.raw);
};

const submitForm = () => {
  addGoodsFn();
};
</script>

<style scoped>
::v-deep .avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  border: 1px dashed #c0c0c0;
}
</style>
